package cn.com.czpb.client.module.news.activity;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import cn.com.czpb.client.R;
import cn.com.czpb.client.api.InterfaceJsonfile;
import cn.com.czpb.client.app.MToolBarActivity;
import cn.com.czpb.client.app.MyActivitymanager;
import cn.com.czpb.client.model.news.NewsBean;
import cn.com.czpb.client.model.news.NewsListEntity;
import cn.com.czpb.client.model.news.SearchHisBean;
import cn.com.czpb.client.module.news.adapter.HistoryAdapter;
import cn.com.czpb.client.module.news.adapter.NewsItemListViewAdapterNew;
import cn.com.czpb.client.net.Factory;
import cn.com.czpb.client.utils.DeviceUtils;
import cn.com.czpb.client.utils.LogUtils;
import cn.com.czpb.client.utils.StringUtils;
import cn.com.czpb.client.utils.TUtils;

import org.litepal.crud.DataSupport;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by 猪猪侠 on 2017/10/18.
 */

public class SearchActivity extends MToolBarActivity implements BaseQuickAdapter.OnItemChildClickListener, BaseQuickAdapter.RequestLoadMoreListener {
    @BindView(R.id.search_ll)
    LinearLayout searchLl;
    @BindView(R.id.search_edittext_id)
    EditText searchEdittextId;
    @BindView(R.id.tv_cancel_id)
    TextView tvCancelId;
    @BindView(R.id.img_clear_id)
    ImageView imgClearId;
    @BindView(R.id.ll_history_id)
    LinearLayout llHistoryId;
    @BindView(R.id.recy_history_id)
    RecyclerView recyHistoryId;
    @BindView(R.id.recycler_newslist_id)
    RecyclerView recyclerNewslistId;
    @BindView(R.id.search_none_tv)
    TextView search_none_tv;
    private HistoryAdapter historyAdapter;
    @BindView(R.id.ll_back)
    LinearLayout ll_back;

    private int page = 1;
    private static final int pageSize = 15;
    private boolean isRefresh = false;
    private boolean mFlagRefresh=true;
    private NewsItemListViewAdapterNew adapter;

    @Override
    public void initView() {
        ll_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
        LinearLayoutManager layoutManager = new LinearLayoutManager(activity);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyHistoryId.setLayoutManager(layoutManager);

        LinearLayoutManager layoutManager2 = new LinearLayoutManager(activity);
        layoutManager2.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerNewslistId.setLayoutManager(layoutManager2);


        recyclerNewslistId.setVisibility(View.GONE);

        historyAdapter = new HistoryAdapter(null);
        recyHistoryId.setAdapter(historyAdapter);
        historyAdapter.setOnItemChildClickListener(this);
        adapter = new NewsItemListViewAdapterNew(activity,null,false);
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                NewsBean newsBean = (NewsBean) adapter.getItem(position);
                switch (view.getId()){
                    case R.id.newsItem_root:
                        MyActivitymanager.pushActivity(activity, newsBean, "", "newsitem",newsBean.getRvalue());
                        break;
                }
            }
        });
        adapter.setOnLoadMoreListener(this, recyclerNewslistId);
        recyclerNewslistId.setAdapter(adapter);
    }

    @Override
    public void initData() {
        udaptRecodeListView();
        searchEdittextId.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (inputMethodManager.isActive()) {
                        inputMethodManager.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
                    }
                    llHistoryId.setVisibility(View.GONE);
                    recyHistoryId.setVisibility(View.GONE);
                    mFlagRefresh=true;
                    new SearchHisBean(searchEdittextId.getText().toString()).save();
                    getSearchData(searchEdittextId.getText().toString());
                    return true;

                }
                return false;
            }
        });
        searchEdittextId.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                /*隐藏软键盘*/
                    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (inputMethodManager.isActive()) {
                        inputMethodManager.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
                    }
                    if (!StringUtils.isEmpty(searchEdittextId.getText().toString())) {
                        mFlagRefresh=true;
                        new SearchHisBean(searchEdittextId.getText().toString()).save();
                        getSearchData(searchEdittextId.getText().toString());
                    }
                    return true;
                }else if(keyCode == KeyEvent.KEYCODE_DEL && event.getAction() == KeyEvent.ACTION_DOWN){
                    search_none_tv.setVisibility(View.GONE);
                }
                return false;
            }
        });
        searchEdittextId.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(s.length() == 0){
                    recyHistoryId.setVisibility(View.VISIBLE);
                    udaptRecodeListView();
                }
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    protected int setLayoutId() {
        return R.layout.activity_search;
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        SearchHisBean bean = historyAdapter.getItem(position);
        String content = bean.getContent();
        searchEdittextId.setText(content);
        searchEdittextId.setSelection(content.length());
        mFlagRefresh=true;
        getSearchData(content);
    }

    private void getSearchData(String content) {
        Map<String, String> map = new HashMap<>();
        map.put("siteid", InterfaceJsonfile.SITEID);
        map.put("content", content);
        map.put("Page", page + "");
        map.put("PageSize", pageSize + "");
        map.put("device", DeviceUtils.getMyUUID(activity));
        if (spu.getUser()!=null){
            map.put("uid",spu.getUser().getUid());
        }

        Factory.provideHttpService().newsSearch(map)
                .subscribeOn(Schedulers.io())
                .filter(new Func1<NewsListEntity, Boolean>() {
                    @Override
                    public Boolean call(NewsListEntity entity) {
                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<NewsListEntity>() {
                    @Override
                    public void call(NewsListEntity entity) {
                        if ("200".equals(entity.code)) {
                            search_none_tv.setVisibility(View.GONE);
                            setListData(entity.data);
                        }else{
                            search_none_tv.setVisibility(View.VISIBLE);
                            TUtils.toast("无内容");
                            setListData(null);
                        }

                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        adapter.loadMoreFail();
                    }
                });
    }
    public void setListData(List<NewsBean> list) {
        llHistoryId.setVisibility(View.GONE);
        recyclerNewslistId.setVisibility(View.VISIBLE);
        recyHistoryId.setVisibility(View.GONE);
        if (mFlagRefresh){
            adapter.setNewData(list);
            adapter.notifyDataSetChanged();
        }else{
            adapter.addData(list);
            adapter.notifyDataSetChanged();
            adapter.loadMoreComplete();
        }
        LogUtils.i("size-->"+adapter.getData().size());
        if (list.size()<pageSize){
            //关闭刷新
            adapter.loadMoreEnd(true);
        }
    }


    @OnClick({R.id.search_ll,R.id.tv_cancel_id, R.id.img_clear_id})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.search_ll:
                String con = searchEdittextId.getText().toString();
                if (null == con || "".equals(con)) {
                    TUtils.toast("请输入内容");
                    return;
                }
                new SearchHisBean(con).save();
                InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.hideSoftInputFromWindow(searchEdittextId.getWindowToken(), 0);
                getSearchData(con);
                break;
            case R.id.tv_cancel_id:
//                llHistoryId.setVisibility(View.VISIBLE);
//                recyHistoryId.setVisibility(View.VISIBLE);
//                recyclerNewslistId.setVisibility(View.GONE);
//                searchEdittextId.setText("");
                activity.finish();
                break;
            case R.id.img_clear_id:
                llHistoryId.setVisibility(View.GONE);
                DataSupport.deleteAll(SearchHisBean.class);
                historyAdapter.setNewData(null);
                break;
        }
    }


    private void udaptRecodeListView() {
        historyAdapter.setNewData(null);
        final List<SearchHisBean> list = DataSupport.findAll(SearchHisBean.class);
        LogUtils.i("list-->" + list.size());
        if (null != list && list.size() > 0) {
            Collections.reverse(list);
        }
        LogUtils.i("收藏数据--->" + null);
        if (null != list && list.size() > 0) {
            recyHistoryId.setVisibility(View.VISIBLE);
            LogUtils.i("收藏数据--->" + list.get(0).getContent());
            llHistoryId.setVisibility(View.VISIBLE);
            historyAdapter.addData(list);
            historyAdapter.notifyDataSetChanged();
        } else {recyHistoryId.setVisibility(View.GONE);

            llHistoryId.setVisibility(View.GONE);

        }
    }

    @Override
    public void onLoadMoreRequested() {
        mFlagRefresh=false;
        page++;
        getSearchData(searchEdittextId.getText().toString());
    }
}
